#include <iostream>
#include <cstdlib>
#include <unistd.h>
#include <strings.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <pthread.h>

void Usage(const std::string proc)
{
    std::cout << "\n\tUsage: " << proc << " serverip serverport\n"
              << std::endl;
}

struct ThreadData
{
    std::string serverip;
    struct sockaddr_in server;
    int sockfd;
};

void *Recv_massege(void *args)
{
    ThreadData *td = static_cast<ThreadData *>(args);
    char buff[1024];
    while (true)
    {
        memset(buff, 0, sizeof(buff));
        struct sockaddr_in tmp;
        socklen_t len = sizeof(tmp);
        ssize_t n = recvfrom(td->sockfd, buff, sizeof(buff), 0, (struct sockaddr *)(&tmp), &len);
        if (n > 0)
        {
            buff[n] = 0;
            std::cerr<< buff << std::endl;
        }
    }
}

void *Send_massege(void *args)
{
    ThreadData *td = static_cast<ThreadData *>(args);
    std::string massege;
    socklen_t len = sizeof(td->server);

    while (true)
    {
        std::cout << "Please Enter@ ";
        getline(std::cin, massege);
        // 1. 数据 2. 给谁发
        sendto(td->sockfd, massege.c_str(), massege.size(), 0, (struct sockaddr *)&(td->server), len);
    }
}
// ./udpclient serverip serverport
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        exit(0);
    }

    std::string serverip = argv[1];
    uint16_t serverport = std::stoi(argv[2]);
    ThreadData td;
    bzero(&td.server, sizeof(td.server));

    td.server.sin_addr.s_addr = inet_addr(serverip.c_str());
    td.server.sin_family = AF_INET;
    td.server.sin_port = htons(serverport);

    td.sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (td.sockfd < 0)
    {
        std::cout << "sock erro" << std::endl;
        exit(1);
    }
    td.serverip = serverip;

    // client 要bind吗？要！只不过不需要用户显示的bind！一般有OS自由随机选择！
    // 一个端口号只能被一个进程bind，对server是如此，对于client，也是如此！
    // 其实client的port是多少，其实不重要，只要能保证主机上的唯一性就可以！
    // 系统什么时候给我bind呢？首次发送数据的时候

    // 创建两个线程，分别收发数据
    pthread_t recv_tid, send_tid;
    pthread_create(&recv_tid, nullptr, Recv_massege, &td);
    pthread_create(&send_tid, nullptr, Send_massege, &td);

    pthread_join(recv_tid, nullptr);
    pthread_join(send_tid, nullptr);

    return 0;
}
